import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

// 创建axios实例
const service = axios.create({
    baseURL: 'http://www.tp5.1.com',
    timeout: 10000 * 6 // 超时时常 
});

// request拦截器
service.interceptors.request.use(
    config => {
        // token
        // if (!config.headers.token) {
        //     config.headers['token'] = getToken()
        // }
        // get请求映射params参数
        if (config.method === "get" && config.params) {
            let url = config.url + "?";
            for (const propName of Object.keys(config.params)) {
                const value = config.params[propName];
                var part = encodeURIComponent(propName) + "=";
                if (value !== null && typeof value !== "undefined") {
                    if (typeof value === "object") {
                        for (const key of Object.keys(value)) {
                            let params = propName + "[" + key + "]";
                            var subPart = encodeURIComponent(params) + "=";
                            url +=
                                subPart + encodeURIComponent(value[key]) + "&";
                        }
                    } else {
                        url += part + encodeURIComponent(value) + "&";
                    }
                }
            }
          
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        return config;
    },
    error => {
        Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    res => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 1;
        // token 校验失败 拦截到登录页面
        if (code === 400) { 
            this.$cookie.remove('userName');
            // 退回到登录界面
            this.$router.push("/login");
        }
    },
    error => {
        let {
            message
        } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            let errorObj = error.response.data;
            if (errorObj.status == 500) {
                message = "后端接口调用失败，请联系管理员！";
            } 
        }
        Message({
            message: message,
            type: "error"
        });
        return Promise.reject(error);
    }
);
export default service;
